<template>
  <div class="login">
    <!-- from组件 -->
    <el-form :model="form" :rules="rules" ref="form" label-width="80px" label-position="top">
      <el-form-item label="用户名" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit"  v-loading="isLoading">登录</el-button>
        <el-button @click="onRest">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login } from '@/services/user'

export default {
  name: 'Login',
  data () {
    return {
      form: {
        phone: '18201288771',
        password: '111111'
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1\d{10}$/, message: '请输入正确手机号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { length: 6, max: 18, message: '6位到18位密码', trigger: 'blur' }
        ]
      },
      isLoading: false
    }
  },
  methods: {
    onRest () {
      this.form = {}
    },
    async onSubmit () {
      try {
        // 表单验证
        await this.$refs.form.validate()
        // 发送请求
        this.isLoading = true
        const { data } = await login(this.form)
        this.isLoading = false
        // 响应处理
        if (data.state !== 1) {
          return this.$message.error(data.message)
        }
        // 当登陆成功后，记录登录状态，存储到vuex中
        this.$store.commit('setUser', data.content)
        // 跳转至首页
        this.$router.push(this.$route.query.lastUrl || '/')
        this.$message.success('登陆成功')
      } catch (err) {
        // catch捕获错误并抛出
        console.log(err)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login{
  //容器盛满高
  height: 100vh;
  display: flex;
  //内容水平居中
  justify-content: center;
  align-items: center;
}
.el-form{
  background-color: #fff;
  width: 300px;
  padding: 20px;
  border-radius: 10px;
  .el-button{
    width: 100%;
    margin-top: 10px;
    margin-left: 0;
  }
}
</style>
